#include "semantic_reasoner.h"
#include <algorithm>

SemanticReasoningResult SemanticReasoner::reason(const std::vector<WuBiSymbol>& inputSymbols) {
    // 1. 激活相关知识
    auto activatedKnowledge = activateKnowledge(inputSymbols);
    
    // 2. 应用推理规则
    auto intermediateResults = applyInferenceRules(inputSymbols, activatedKnowledge);
    
    // 3. 整合结果
    auto finalResult = integrateResults(intermediateResults);
    
    return finalResult;
}

std::set<KnowledgeUnit*> SemanticReasoner::activateKnowledge(const std::vector<WuBiSymbol>& symbols) {
    std::set<KnowledgeUnit*> activated;
    
    for (const auto& symbol : symbols) {
        // 基于语义相似度激活相关知识
        for (auto* knowledge : knowledgeBase) {
            if (knowledge->shouldBeActivated(symbol)) {
                activated.insert(knowledge);
            }
        }
    }
    
    return activated;
}

std::vector<SemanticReasoningResult> SemanticReasoner::applyInferenceRules(
    const std::vector<WuBiSymbol>& symbols,
    const std::set<KnowledgeUnit*>& activatedKnowledge) {
    
    std::vector<SemanticReasoningResult> results;
    
    for (const auto& rule : inferenceRules) {
        if (rule.canApply(symbols, activatedKnowledge)) {
            auto result = rule.apply(symbols, activatedKnowledge);
            results.push_back(result);
        }
    }
    
    return results;
}

SemanticReasoningResult SemanticReasoner::integrateResults(
    const std::vector<SemanticReasoningResult>& results) {
    
    SemanticReasoningResult integratedResult;
    double totalConfidence = 0.0;
    
    for (const auto& result : results) {
        // 合并推断出的符号
        integratedResult.inferredSymbols.insert(
            integratedResult.inferredSymbols.end(),
            result.inferredSymbols.begin(),
            result.inferredSymbols.end()
        );
        
        // 合并激活的知识
        integratedResult.activatedKnowledge.insert(
            integratedResult.activatedKnowledge.end(),
            result.activatedKnowledge.begin(),
            result.activatedKnowledge.end()
        );
        
        // 计算加权置信度
        totalConfidence += result.confidence;
    }
    
    integratedResult.confidence = totalConfidence / std::max(1.0, (double)results.size());
    
    return integratedResult;
}